<?php
/**
* @copyright (C) 2003 - 2004 SystN International Pty Ltd.
* @license http://www.SystN.com
* SystN is Free Software
*/

Class Dirver{
	//连接数据库
	function DBLink($dba=''){
		$this->LinkID = @pg_connect("host=".$dba['dbhost']." dbname=".$dba['dbname']." user=".$dba['dbuser']." password=".$dba['dbpass']) or die("Connect to PostgreSQL (".$dba['dbhost'].",".$dba['dbuser'].") failed");
		return $this->LinkID;
	}
	
	//查询语句
	function query($query,$limit='') {
		$this -> nums ++;
		//检测如果有限制数据集则处理
		if($limit>0){
			$query = $query.' LIMIT '.$limit;
		}
		$this-> Lists .= $query.'<br>';
		return @pg_query($this->LinkID,$query);
	}
	
	//返回数组资料
	function fetch_array($query) {
		return @pg_fetch_array($query, null, PGSQL_ASSOC);
	}
	
	//取得返回列的数目
	function num_rows($query){
		return @pg_num_rows($query);
	}
	
	//返回单列的各字段
	function fetch_row($query,$i='') {
		return @pg_fetch_row($query,$i);
	}
	
	//返回最后一次使用 INSERT 指令的 ID
	function insert_id(){
		$v = $this->version();
		
		$table	= func_num_args() > 0 ? func_get_arg(0) : null;
		$column	= func_num_args() > 1 ? func_get_arg(1) : null;
		
		if ($table == null && ereg('8.1',$v)){
			$row  = $this->fetch_array($this->query('SELECT LASTVAL() AS id'));
		}elseif ($table != null && $column != null && $v >= '8.0'){
			$sql  = sprintf("SELECT pg_get_serial_sequence('%s','%s') AS seq", $table, $column);
			$rows = $this->fetch_array($this->query($sql));
			$sqls = sprintf("SELECT CURRVAL('%s') AS id", $rows->seq);
			$row  = $this->fetch_array($this->query($sqls));
		}elseif ($table != null){
			// seq_name passed in table parameter
			$sql  = sprintf("SELECT CURRVAL('%s') AS id", $table);
			$row  = $this->fetch_array($this->query($sql));
		}else{
			return pg_last_oid($this->result_id);
		}
		
		return $row['id'];
	}
	
	//关闭当前数据库连接
	function close(){
		return @pg_close($this->LinkID);
	}
	
	//检测版本
	function version(){
		$vas = pg_version($this->LinkID);
		return $vas['client'];
	}
	
	//查询语句数
	function sql_num(){
		return $this -> nums;
	}
	
	//查询语句列表
	function sql_debug(){
		return $this-> Lists;
	}
	
	
}
?>